<template>
  <div class="app-container">
    <div class="top">
      <div class="operate"></div>
      <el-form
        :model="queryParams"
        ref="queryForm"
        :inline="true"
        label-width="68px"
      >
        <el-form-item>
          <organizationCascader
            :clearData="{
              factory:false,
              workshop:true,
              line:true
            }"
            :arrData="queryParams"
            :isAllList="true"
            @change="change"
          ></organizationCascader>
        </el-form-item>

        <el-form-item prop="month">
          <el-date-picker
            v-model="nowDate"
            type="month"
            placeholder="选择年月"
            size="small"
            :clearable="false"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            icon="el-icon-search"
            size="mini"
            @click="handleQuery"
            >搜索</el-button
          >
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
            >重置</el-button
          >
        </el-form-item>
      </el-form>
    </div>

    <div class="date-content">
      <el-calendar v-model="nowDate" :first-day-of-week="7">
        <template v-slot:dateCell="{ date, data }">
          <div
            :class="['day-content', { 'pass-time': isDisabled(date) }]"
            @click.stop="showDetail(date, data)"
          >
            <span class="day">{{ data.day.split("-")[2] }}</span>
            <span
              v-if="statusData[data.day] == 'OFF'"
              class="status off-work"
              size="mini"
              >休</span
            >
            <span
              v-else-if="statusData[data.day] == 'NOT'"
              class="status off-work"
              size="mini"
              >班/休</span
            >
            <span
              v-else-if="statusData[data.day] == 'ON'"
              class="status"
              size="mini"
              >班</span
            >
          </div>
        </template>
      </el-calendar>
    </div>
    <weekdaySetDialog
      :visible.sync="weekdayDialog.visible"
      :weekData="weekData"
      :baseData="baseData"
      :weekdayItem="weekdayItem"
      @submit-success="getList"

    />
    <weekdayDetail
      :visible.sync="weekdayDetail.visible"
      :weekData="weekData"
      :baseData="baseData"
      :weekdayItem="weekdayItem"
      :configDisabled="weekdayDetail.configDisabled"
      @config-click="handleStatusChange"
    />
  </div>
</template>
<script>
import organizationCascader from "@/views/components/organizationCascader";
import weekdaySetDialog from "./weekdaySetDialog";
import weekdayDetail from "./weekdayDetail";
import { listLineProduceStatus,changeLineProduceStatus } from "@/api/shifts/userChange";
import { mapGetters } from "vuex";
const weekStr = ['日','一','二','三','四','五','六']
export default {
  name: "UserArrangement",
  components: {organizationCascader,weekdaySetDialog,weekdayDetail },
  data() {
    return {
      queryParams: {
        factoryDeptCode: null,
        factoryDeptId: null,
        factoryName:null,
        workshopCode: null,
        workshopId:null,
        workshopName:null,
        lineId: null,
        lineName:null,
        yearStr:new Date().getFullYear(),
        monthStr:(new Date().getMonth()+1) > 9 ? new Date().getMonth()+1 : "0"+(new Date().getMonth()+1)
      },
      nowDate: new Date(),
      newDateTime: new Date().setHours(0, 0, 0, 0),
      detailDialog: {
        visible: false,
        data: {}
      },
      statusData: {},
      workItem:{},
      currentDate:{},
      weekdayItem:{},
      weekData:{},
      baseData:{},
      weekdayDialog:{
        visible: false,
      },
      weekdayDetail:{
        visible: false,
        configDisabled: true
      }
    };
  },

  created() {
    const result = this.getOwnFirstLine()
    this.queryParams.factoryDeptCode = result[0]?.factoryDeptCode;
    this.queryParams.factoryDeptId = result[0]?.factoryDeptId;
    this.queryParams.factoryName = result[0]?.factoryName;
    this.queryParams.workshopCode = result[1]?.workshopCode;
    this.queryParams.workshopId = result[1]?.workshopId;
    this.queryParams.workshopName = result[1]?.workshopName;
    this.queryParams.lineId = result[2]?.lineId;
    this.queryParams.lineName = result[2]?.lineName;
    this.getList()
  },

  methods: {
    // 查询车间或产线当月生产状态
    getList() {
      let self = this;
      if(!this.queryParams.factoryDeptId){
        this.msgError("请选择工厂");
        return
      }
      const {factoryDeptId,workshopId,lineId,yearStr,monthStr} = this.queryParams
      const parmas = {
        factoryDeptId,
        workshopId,
        lineId,
        yearStr,
        monthStr
      }
      listLineProduceStatus(parmas)
        .then((res) => {
          if(res.code == 200){
            const dataList = res.data;
            let classesDutyList = []
            for (let key in dataList){
              let day = key > 9 ? key : "0"+key;
              let dataKey = this.queryParams.yearStr+"-"+this.queryParams.monthStr+"-"+day+'';
              if(dataList[key]){
                classesDutyList = dataList[key]?.classesDutyList;
                if(classesDutyList?.length){//工厂，车间，产线三个层级数据
                  let lineList = [];
                  classesDutyList.forEach((ele,index) => {
                    if(ele?.workshopDutyInfoList?.length){
                      ele.workshopDutyInfoList.forEach(item => {
                        if(item?.lineDutyInfoList?.length){
                          item.lineDutyInfoList.forEach(tar => {
                            lineList.push(tar);
                            this.$set(this.currentDate,dataKey,lineList)
                          })
                        }
                        else{
                          lineList.push({
                            produceStatus:"ON"
                          });
                          this.$set(this.currentDate,dataKey,lineList)
                        }
                      })
                    }
                    else{
                      lineList.push({
                        produceStatus:"ON"
                      });
                      this.$set(this.currentDate,dataKey,lineList)
                    }
                  })
                  for (let idx in this.currentDate){
                    if(this.currentDate[idx].every(this.isExistRest)){//所有产线都是工作日
                      this.$set(this.statusData,idx,"ON")
                    }
                    else{
                      if(!this.currentDate[idx].some(this.isExistRest)){//都是休息日
                        this.$set(this.statusData,idx,"OFF")
                      }
                      else{
                        this.$set(this.statusData,idx,"NOT")
                      }
                    }
                  }
                }
              }
              else{//没有配置休息和工作日
                this.$nextTick(()=>{
                  this.$set(this.statusData,dataKey,"ON")
                })
              }
              this.$set(this.workItem,dataKey,dataList[key])
            }
          }
        })
        .catch(() => {

        });
    },

    isExistRest(value, index, ar){
      if(value?.produceStatus == "ON") {
        return true;
      }
      else {
        return false;
      }
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.getList();
    },

    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams.lineId = null;
      this.queryParams.lineName = null;
      this.queryParams.workshopCode = null;
      this.queryParams.workshopId = null;
      this.queryParams.workshopName = null;
      this.getList();
    },

    isDisabled(date) {
      return date.getTime() < this.newDateTime
    },

    // 切换状态
    handleStatusChange(date, data) {
      this.weekdayDetail.visible = false;
      this.weekdayDialog.visible = true;
    },

    //查看工作安排详情
    showDetail(date, data){
      if(!this.queryParams.factoryDeptId){
        this.msgWarning("请选择工厂");
        return
      }
      this.packageData(date, data);
      this.weekdayDetail.configDisabled = this.isDisabled(date);
      this.weekdayDetail.visible = true;
    },

    //组装数据
    packageData(date, data){
      const days = data.day.split('-')
      const week = date.getDay();
      const{factoryDeptId,workshopId,lineId,factoryName,workshopName,lineName} = this.queryParams
      this.weekData = {
        year:days[0],
        month:days[1],
        day:days[2],
        week:`星期${weekStr[week]}`,
      }
      this.baseData = {
        factoryDeptId,
        workshopId,
        lineId,
        factoryName,
        workshopName,
        lineName
      }
      this.weekdayItem = this.workItem[data.day];
    },

    change({factoryDeptCode,factoryDeptId,factoryName,workshopCode,workshopId,workshopName,lineId,lineCode,lineName}){
      this.queryParams = Object.assign({},{
        factoryDeptCode,
        factoryDeptId,
        factoryName,
        workshopCode,
        workshopId,
        workshopName,
        lineId,
        lineCode,
        lineName
      },
      {
        yearStr:this.queryParams.yearStr,
        monthStr:this.queryParams.monthStr
      })
      this.getList();
    }
  },
  watch:{
    nowDate(newVal){
      if(newVal){
        const date = this.parseTime(newVal).split("-");
        this.queryParams.yearStr = date[0];
        this.queryParams.monthStr = date[1];
        this.statusData = {};
        this.workItem = {};
        this.currentDate = {};
        this.getList();
      }
    }
  }
};
</script>
<style lang="scss" scoped>
.top {
  height: 44px;
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
}
::v-deep .el-calendar-table {
  thead th::before {
    content: "星期";
  }
  td.is-selected {
    background: none;
  }
  td.is-today {
    color: inherit;
  }
  .el-calendar-day {
    padding: 0;
    &:hover {
      background: none;
      cursor: pointer;
    }
  }
}
.day-content {
  width: 100%;
  height: 100%;
  padding: 16px;
  .day {
    display: inline-block;
    vertical-align: middle;
    width: 50px;
    height: 34px;
    line-height: 34px;
    text-align: center;
  }
  .status {
    display: inline-block;
    vertical-align: middle;
    width: 36px;
    height: 26px;
    line-height: 26px;
    text-align: center;
    border-radius: 6px;
    font-size: 14px;
    background: #88c446;
    color: #ffffff;
    cursor: pointer;
    &.off-work {
      background: #f56c6c;
    }
  }
  &.pass-time {
    background-color: #f5f5f5;
    .status {
      opacity: 0.75;
    }
  }
}

::v-deep .el-calendar-table:not(.is-range) td.prev,
::v-deep .el-calendar-table:not(.is-range) td.next {
  cursor: not-allowed;
  pointer-events: none;
}
.prev>.el-calendar-day>p{
  display: none;
}
.next>.el-calendar-day>p{
  display: none;
}

</style>
